package com.goockr.litepal;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.goockr.litepal.Tables.Book;

import org.litepal.LitePal;
import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.SaveCallback;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    SQLiteDatabase db;
    ListView lv_DatabaseList;
    LitepalAdapter litepalAdapter;
    List<Book>books=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv_DatabaseList=(ListView)findViewById(R.id.lv_DatabaseList);
        litepalAdapter=new LitepalAdapter(books);
        lv_DatabaseList.setAdapter(litepalAdapter);
        finaAll();
    }


    private void finaAll()
    {
        List<Book> bookList= DataSupport.findAll(Book.class);

        books.clear();
        books.addAll(bookList);
        litepalAdapter.notifyDataSetChanged();

    }

    void onCliceBtn(View v){
        switch (v.getId())
        {
            case  R.id.bt_Add:
                final Book book=new Book();
                book.setBookName("假如给我四天光明");
                book.setAuthor("张三");
                book.setPrice(23.32);
                book.saveAsync().listen(new SaveCallback() {
                    @Override
                    public void onFinish(boolean success) {
                        Toast.makeText(MainActivity.this,"保存状态："+String.valueOf(success),Toast.LENGTH_SHORT).show();
                        if (success){
                            books.add(book);
                            litepalAdapter.notifyDataSetChanged();
                        }
                    }
                });

                break;
            case R.id.bt_Delete:
                if (books.size()<=0)return;
                int state = DataSupport.delete(Book.class,books.get(books.size()-1).getId());
                Toast.makeText(MainActivity.this,"删除状态："+String.valueOf(state),Toast.LENGTH_SHORT).show();
                if (state>=1)finaAll();
                break;
            case R.id.bt_CreateDB:
                db = LitePal.getDatabase();
                v.setEnabled(false);
                v.setBackground(getResources().getDrawable(R.color.colorAccent));
                break;

        }
    }
}
